package gui.screens;

import gui.CanvasManager;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import application.MainController;
import domain.Game;

/**
 * Class for the login screen.
 * @author Sandra Mayer
 *
 */
public class LoginScreen extends Form implements CommandListener {
	
	private static String REGISTER = "Register";
	
	private TextField userName;
	private Command cancelCmd;
	private Command loginCmd;
	private Game game;

	/**
	 * Constructor.
	 * @param game the Game Object
	 */
	public LoginScreen(Game game) {
		super("Register");
		CanvasManager.setCurScreen(this);
		userName = new TextField("Username:", "", 10, TextField.ANY);
	    cancelCmd = new Command("Cancel", Command.CANCEL, 2);
	    loginCmd = new Command(REGISTER, Command.OK, 2);
	    this.game = game;
		
	    this.append(userName);
	    this.addCommand(cancelCmd);
	    this.addCommand(loginCmd);
	    this.setCommandListener(this);
	}

	/**
	 * Validates the user input.
	 * @param name the name of the user
	 */
	public void validateUser(String name) {
		if (MainController.getInstance().register(game, name)) {
			CanvasManager.setCurrent(new RBCanvas());
		} else {
			tryAgain();
		}
	}     

	/**
	 * Shows an error message if the name was wrong or already in use.
	 *
	 */
	public void tryAgain() {
		Alert error = new Alert("Login Incorrect", "Please try again", null, AlertType.ERROR);
		error.setTimeout(Alert.FOREVER);
		userName.setString("");
		CanvasManager.setCurrent(error, this);
	}

	/**
	 * Does the command action.
	 */
	public void commandAction(Command cmd, Displayable d) {
		if(cmd == cancelCmd) {
			CanvasManager.showOldScreen();
		} else if(cmd == loginCmd) {
			validateUser(userName.getString());
		}
	}
}
